package com.wqj.ride.happyriding.base;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.transition.Transition;
import android.transition.TransitionInflater;

import com.wqj.ride.happyriding.R;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/12/15.
 */

public class BaseTransitionInActivity extends AppCompatActivity {
    public static final String EXTRA_TRANSITION = "EXTRA_TRANSITION";
    public static final String TRANSITION_FADE_FAST = "FADE_FAST";
    public static final String TRANSITION_FADE_SLOW = "FADE_SLOW";
    public static final String TRANSITION_SLIDE_RIGHT = "SLIDE_RIGHT";
    public static final String TRANSITION_SLIDE_BOTTOM = "SLIDE_BOTTOM";
    public static final String TRANSITION_EXPLODE = "EXPLODE";
    public static final String TRANSITION_EXPLODE_BOUNCE = "EXPLODE_BOUNCE";

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String transition = getIntent().getStringExtra(EXTRA_TRANSITION);
        switch (transition) {
            case TRANSITION_SLIDE_RIGHT:
                Transition transitionSlideRight =
                        TransitionInflater.from(this)
                                .inflateTransition(R.transition.slide_right);
                getWindow().setEnterTransition(transitionSlideRight);
                break;
            case TRANSITION_SLIDE_BOTTOM:
                Transition transitionSlideBottom =
                        TransitionInflater.from(this)
                                .inflateTransition(R.transition.slide_bottom);
                getWindow().setEnterTransition(transitionSlideBottom);
                break;
            case TRANSITION_FADE_FAST:
                Transition transitionFadeFast =
                        TransitionInflater.from(this)
                                .inflateTransition(R.transition.fade_fast);
                getWindow().setEnterTransition(transitionFadeFast);
                break;
            case TRANSITION_FADE_SLOW:
                Transition transitionFadeSlow =
                        TransitionInflater.from(this)
                                .inflateTransition(R.transition.fade_slow);
                getWindow().setEnterTransition(transitionFadeSlow);
                break;
            case TRANSITION_EXPLODE:
                Transition transitionExplode =
                        TransitionInflater.from(this)
                                .inflateTransition(R.transition.explode);
                getWindow().setEnterTransition(transitionExplode);
                break;
            case TRANSITION_EXPLODE_BOUNCE:
                Transition transitionExplodeBounce =
                        TransitionInflater.from(this)
                                .inflateTransition(R.transition.explode_bounce);
                getWindow().setEnterTransition(transitionExplodeBounce);
                break;
        }
    }

    /**
     * Created by Administrator on 2017/12/15.
     */

    public static class CheckPermissionsActivity extends AppCompatActivity {
        public static final int PERMISSIONS_GRANTED = 0;
        public static final int PERMISSIONS_DENIED = 1;

        private static final int PERMISSION_REQUEST_CODE = 0;
        private static final String EXTRA_PERMISSIONS =
                "me.chunyu.clwang.permission.extra_permission";
        private static  final String PACKAGE_URL_SCHEME = "package:";

        private PermissionChecker mChecker;
        //private boolean isRequireCheck = true;
        private boolean isNeedCheck = true;

        protected String[] needPermissions = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.BLUETOOTH
        };

        @Override
        protected void onResume() {
            super.onResume();
    //        if (isRequireCheck) {
    //            String[]  permissions = getPermissions();
    //            if (mChecker.lacksPermissions(permissions)) {
    //                requestPermissions(permissions);
    //            } else{
    //                allPermissionsGranted();
    //            }
    //        } else {
    //            isRequireCheck = true;
    //        }

            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                if (isNeedCheck) {
                    checkPermissions(needPermissions);
                }
            }
        }

        private void checkPermissions(String... permissions) {
            try {
                if (Build.VERSION.SDK_INT >= 23
                        && getApplicationInfo().targetSdkVersion >= 23) {
                    List<String> needRequestPermissionList = findDeniedPermissions(permissions);
                    if (null != needRequestPermissionList
                            && needRequestPermissionList.size() > 0) {
                        String[] array = needRequestPermissionList
                                .toArray(new String[needRequestPermissionList.size()]);
                        Method method = getClass()
                                .getMethod("requestPermissions", new Class[]{String[].class,
                                int.class});

                        method.invoke(this, array, PERMISSION_REQUEST_CODE);
                    }
                }
            } catch (Throwable e) {

            }
        }

        private List<String> findDeniedPermissions(String[] permissions) {
            List<String> needRequestPermissionList = new ArrayList<String>();
            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                try {
                    for (String perm : permissions) {
                        Method checkSelfMethod = getClass()
                                .getMethod("checkSelfPermission", String.class);
                        Method shouldShowRequestPermissionRationaleMethod
                                = getClass().getMethod("shouldShowRequestPermissionRationale",
                                String.class);
                        if ((Integer) checkSelfMethod.invoke(this, perm)
                                != PackageManager.PERMISSION_GRANTED
                                || (Boolean) shouldShowRequestPermissionRationaleMethod
                                .invoke(this, perm)) {
                            needRequestPermissionList.add(perm);
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            return needRequestPermissionList;
        }

        public void onRequestPermissionsResult(int requestCode,
                                               String[] permissions, int[] paramArrayOfInt) {
            if (requestCode == PERMISSION_REQUEST_CODE) {
                if (!verifyPermissions(paramArrayOfInt)) {
                    showMissingPermissionDialog();
                    isNeedCheck = false;
                }
            }
        }

        private boolean verifyPermissions(int[] grantResults) {
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
            return true;
        }


        private void showMissingPermissionDialog() {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.notifyTitle);
            builder.setMessage(R.string.notifyMsg);

            // 拒绝, 退出应用
            builder.setNegativeButton(R.string.cancel,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });

            builder.setPositiveButton(R.string.setting,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startAppSettings();
                        }
                    });

            builder.setCancelable(false);

            builder.show();
        }

    //    private String[] getPermissions() {
    //        return getIntent().getStringArrayExtra(EXTRA_PERMISSIONS);
    //    }
    //
    //    private void requestPermissions(String... permissions) {
    //        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
    //    }
    //
    //    private void allPermissionsGranted() {
    //        setResult(PERMISSIONS_GRANTED);
    //        finish();
    //    }

    //    @Override
    //    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    //        //
    //        if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
    //            isRequireCheck = true;
    //            allPermissionsGranted();
    //        } else {
    //            isRequireCheck = false;
    //            showMissingPermissionDislog();
    //        }
    //    }
    //
    //    private boolean hasAllPermissionsGranted(int[] grantResults) {
    //        for (int grantResult : grantResults) {
    //            if (grantResult == PackageManager.PERMISSION_DENIED) {
    //                return false;
    //            }
    //        }
    //        return true;
    //    }
    //
    //    private void showMissingPermissionDislog() {
    //        AlertDialog.Builder builder = new AlertDialog.Builder(PermissionsActivity.this);
    //        builder.setTitle("help");
    //        builder.setMessage("请授权");
    //
    //        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
    //            @Override
    //            public void onClick(DialogInterface dialogInterface, int which) {
    //                setResult(PERMISSIONS_DENIED);
    //                finish();
    //            }
    //        });
    //
    //        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
    //            @Override
    //            public void onClick(DialogInterface dialogInterface, int i) {
    //                startAppSettings();
    //            }
    //        });
    //
    //        builder.show();
    //    }

        private void startAppSettings() {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
            startActivity(intent);
        }
    }
}
